package com.funcourse.demo.business.oss;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.funcourse.demo.aliyun.oss.ObjectTagger;
import com.funcourse.demo.aliyun.oss.OssConfig;
import com.funcourse.demo.model.CompeteRoom;
import com.funcourse.demo.model.Quiz;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice.Unused;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ObjectReferenceManager {

  @Autowired
  OssConfig ossConfig;
  @Autowired
  ObjectMapper objectMapper;
  @Autowired
  ObjectTagger objectTagger;

  Pattern ossObjectUrLPattern;

  public void referenceCountChangeByQuizCreate(Quiz quiz){
    final List<String> ossObjectNamesFromQuiz = extractOssObjectNameFromQuiz(quiz);
    ossObjectNamesFromQuiz.forEach(objectName->{
      objectTagger.increaseOrInitReferenceTag(1,objectName);
    });
  }

  public void referenceCountChangeByQuizModify(Quiz oldQuiz,Quiz newQuiz){
    final List<String> ossObjectNamesFromOldQuiz = extractOssObjectNameFromQuiz(oldQuiz);
    final List<String> ossObjectNamesFromNewQuiz = extractOssObjectNameFromQuiz(newQuiz);
    //who is in ossObjectNamesFromNewQuiz but not in ossObjectNamesFromOldQuiz
    List<String> newOssObjectNames=new LinkedList<>();
    //who is in ossObjectNamesFromOldQuiz but not in ossObjectNamesFromNewQuiz
    List<String> oldOssObjectNames=new LinkedList<>();

    for(String objectName:ossObjectNamesFromNewQuiz){
      if(ossObjectNamesFromOldQuiz.contains(objectName)){
        continue;
      }
      newOssObjectNames.add(objectName);
    }

    for(String objectName:ossObjectNamesFromOldQuiz){
      if(ossObjectNamesFromNewQuiz.contains(objectName)){
        continue;
      }
      oldOssObjectNames.add(objectName);
    }
    newOssObjectNames.forEach(objectName ->{
      objectTagger.increaseOrInitReferenceTag(1,objectName);
    });

    oldOssObjectNames.forEach(objectName ->{
      objectTagger.increaseOrInitReferenceTag(-1,objectName);
    });
  }

  public void referenceCountChangeByQuizDelete(Quiz quiz){
    final List<String> ossObjectNamesFromQuiz = extractOssObjectNameFromQuiz(quiz);
    ossObjectNamesFromQuiz.forEach(objectName->{
      objectTagger.increaseOrInitReferenceTag(-1,objectName);
    });
  }

  private List<String> extractOssObjectNameFromQuiz(Quiz quiz){
    List<String> result = new LinkedList<>();
    final String quizSearilized;
    try {
      quizSearilized = objectMapper.writeValueAsString(quiz);
    } catch (JsonProcessingException e) {
      log.warn("quizSearilizing failed  ",e);
      return new ArrayList<>(0);
    }
    final Matcher matcher = ossObjectUrLPattern.matcher(quizSearilized);
    while(matcher.find()){
      result.add(matcher.group(1));
    }
    return result;
  }

  @PostConstruct
  public void afterConstruct(){
    // https://huixi-pic-hub.oss-cn-beijing.aliyuncs.com/(*)
    ossObjectUrLPattern = Pattern.compile(ossConfig.getPicDomain().replace(".","\\.")+"/"+"(.{10}\\d{13})");
  }

//  public static void main(String[] args){
//
//    final Pattern compile = Pattern.compile(
//        "https://huixi-user-upload\\.oss-cn-beijing\\.aliyuncs\\.com" + "/" + "(.{10}\\d{13})");
//    final Matcher matcher = compile.matcher("{\n"
//        + "    \"code\": 200,\n"
//        + "    \"msg\": \"\",\n"
//        + "    \"body\": {\n"
//        + "        \"id\": \"5fe71d84c7d1505379fe34e5\",\n"
//        + "        \"roomNumber\": \"558645\",\n"
//        + "        \"ownerId\": \"5fc399bc411cec7d460f3716\",\n"
//        + "        \"organizer\": \"cookie can\",\n"
//        + "        \"quiz\": {\n"
//        + "            \"questions\": [\n"
//        + "                {\n"
//        + "                    \"questionNumber\": 0,\n"
//        + "                    \"questionStem\": \"这个题是个多选题，你猜选啥？\",\n"
//        + "                    \"answerExplanation\": null,\n"
//        + "                    \"questionCoverUrl\": \"https://huixi-user-upload.oss-cn-beijing.aliyuncs.com/yKi22ES3QT1608981005319\",\n"
//        + "                    \"choices\": [\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 0,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"我是A，我是错的\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": false\n"
//        + "                        },\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 1,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"我是B，我是对的\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": true\n"
//        + "                        },\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 2,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"我是C，我也是对的\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": true\n"
//        + "                        },\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 3,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"我是D，我还是对的\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": true\n"
//        + "                        }\n"
//        + "                    ],\n"
//        + "                    \"rightAnswers\": null,\n"
//        + "                    \"timeLimit\": 15,\n"
//        + "                    \"isMultiSel\": false,\n"
//        + "                    \"questionType\": \"SEL_MULTI\"\n"
//        + "                },\n"
//        + "                {\n"
//        + "                    \"questionNumber\": 1,\n"
//        + "                    \"questionStem\": \"我是个单选题， 我带了个图片\",\n"
//        + "                    \"answerExplanation\": null,\n"
//        + "                    \"questionCoverUrl\": \"https://huixi-user-upload.oss-cn-beijing.aliyuncs.com/tOYQ9crXlc1608518246432\",\n"
//        + "                    \"choices\": [\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 0,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"https://huixi-user-upload.oss-cn-beijing.aliyuncs.com/kIeJzJKoGq1608518264946\",\n"
//        + "                            \"choiceType\": \"PIC\",\n"
//        + "                            \"right\": true\n"
//        + "                        },\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 1,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"巴拉巴拉\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": false\n"
//        + "                        },\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 2,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"叽里呱啦\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": false\n"
//        + "                        },\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 3,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"嘻嘻哈哈\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": false\n"
//        + "                        }\n"
//        + "                    ],\n"
//        + "                    \"rightAnswers\": null,\n"
//        + "                    \"timeLimit\": 15,\n"
//        + "                    \"isMultiSel\": false,\n"
//        + "                    \"questionType\": \"SEL_SINGLE\"\n"
//        + "                },\n"
//        + "                {\n"
//        + "                    \"questionNumber\": 2,\n"
//        + "                    \"questionStem\": \"我又是个多选题，嘻嘻！\",\n"
//        + "                    \"answerExplanation\": null,\n"
//        + "                    \"questionCoverUrl\": \"https://huixi-user-upload.oss-cn-beijing.aliyuncs.com/uBE4bKF2di1608518328005\",\n"
//        + "                    \"choices\": [\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 0,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"对的答案\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": true\n"
//        + "                        },\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 1,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"错的答案\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": false\n"
//        + "                        },\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 2,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"又是对的答案\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": true\n"
//        + "                        },\n"
//        + "                        {\n"
//        + "                            \"choiceNumber\": 3,\n"
//        + "                            \"choiceDesc\": null,\n"
//        + "                            \"choiceContent\": \"错的答案2\",\n"
//        + "                            \"choiceType\": \"TEXT\",\n"
//        + "                            \"right\": false\n"
//        + "                        }\n"
//        + "                    ],\n"
//        + "                    \"rightAnswers\": null,\n"
//        + "                    \"timeLimit\": 40,\n"
//        + "                    \"isMultiSel\": false,\n"
//        + "                    \"questionType\": \"SEL_MULTI\"\n"
//        + "                }\n"
//        + "            ],\n"
//        + "            \"coverUrl\": \"https://huixi-user-upload.oss-cn-beijing.aliyuncs.com/FK53h3JCGe1608978802221\",\n"
//        + "            \"description\": \"\",\n"
//        + "            \"name\": \"测试新多选题\",\n"
//        + "            \"isPrivate\": false,\n"
//        + "            \"ownerId\": \"5fc399bc411cec7d460f3716\",\n"
//        + "            \"id\": \"5fe0093fb28b5c185dd17f57\",\n"
//        + "            \"createdTime\": 1608517951159,\n"
//        + "            \"modifyTime\": 1608981024067,\n"
//        + "            \"testedCount\": 0\n"
//        + "        },\n"
//        + "        \"userWithScoreList\": [\n"
//        + "            {\n"
//        + "                \"avatarUrl\": \"https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epw4CyRBvWkxyHtjBC5DVEp9Y3e4RfGmpQSEuiaDWJAz7P8KawGTsfDZ0IvCtc05BibvExPJaicHSrJw/132\",\n"
//        + "                \"nickName\": \"cookie can\",\n"
//        + "                \"weletOpenIds\": [\n"
//        + "                    \"otqBI4_rn-CVypSQJyMMi-KvsIYI\",\n"
//        + "                    \"oIhDf4m8utPKbkF71inuUvunCat4\"\n"
//        + "                ],\n"
//        + "                \"id\": \"5fc399bc411cec7d460f3716\",\n"
//        + "                \"totalScore\": 0,\n"
//        + "                \"ranking\": 1,\n"
//        + "                \"scoreDetails\": []\n"
//        + "            }\n"
//        + "        ],\n"
//        + "        \"roomStatus\": \"CREATED\",\n"
//        + "        \"currentQuestionNO\": 0,\n"
//        + "        \"questionAllAnswered\": false,\n"
//        + "        \"roomType\": \"REAL_TIME\",\n"
//        + "        \"orgnizedTime\": 1608981892013\n"
//        + "    }\n"
//        + "}");
//    while (matcher.find()){
//      System.out.println(matcher.group(1));
//    }
//
//  }

}
